/**
 * @Title:FxService.java
 * @Description:TODO
 * @author shan
 * @date 2015-4-12 上午11:49:31
 */
package com.shan.combo.assist.service;

import java.io.File;
import java.io.IOException;

import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageView;

public class FxService extends Service {

    WindowManager.LayoutParams wmParams;
    // 创建浮动窗口设置布局参数的对象
    WindowManager mWindowManager;

    // Button mFloatView;
    private ImageView view;// 透明窗体

    private static final String TAG = "FxService";

    private static int FIRST_X = 90-45;
    private static int FIRST_Y = 940+45;
    private static int WIDTH = 200;
    private static int HEIGHT = 200;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "oncreat");
        createFloatView();
    }

    public void onStart(Intent intent, int startId) {
        Log.i(TAG, "onStart");

        String action = intent.getAction();

        if ("com.shan.combo.assist.service.draw".equals(action)) {
            view.setVisibility(View.VISIBLE);
            drawLines(intent.getIntArrayExtra("location"));
        } else if ("com.shan.combo.assist.service.clear".equals(action)) {
            view.setVisibility(View.INVISIBLE);
        } else if ("com.shan.combo.assist.service.press".equals(action)) {
            press(1000);
        } else if ("com.shan.combo.assist.service.srceencap".equals(action)) {
            srceenCap();  
        }

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    private void createFloatView() {
        wmParams = new WindowManager.LayoutParams();
        // 获取的是WindowManagerImpl.CompatModeWrapper
        mWindowManager = (WindowManager) getApplication().getSystemService(getApplication().WINDOW_SERVICE);
        Log.i(TAG, "createFloatView--->" + mWindowManager);
        // 设置window type
        wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        // 设置图片格式，效果为背景透明
        wmParams.format = PixelFormat.RGBA_8888;
        // 设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
        wmParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL | LayoutParams.FLAG_NOT_FOCUSABLE | LayoutParams.FLAG_NOT_TOUCHABLE;

        // 调整悬浮窗显示的停靠位置为左侧置顶
        // wmParams.gravity = Gravity.LEFT | Gravity.TOP;
        // 以屏幕左上角为原点，设置x、y初始值，相对于gravity
        wmParams.x = 0;
        wmParams.y = 0;

        // wmParams.width = 720;
        // wmParams.height = 1280;

        // 设置悬浮窗口长宽数据
        wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;

        /*
         * // 设置悬浮窗口长宽数据 wmParams.width = 200; wmParams.height = 80;
         */

        // LayoutInflater inflater = LayoutInflater.from(getApplication());
        // // 获取浮动窗口视图所在布局
        // mFloatLayout = (LinearLayout) inflater.inflate(R.layout.float_layout,
        // null);
        // 添加mFloatLayout

        view = new ImageView(getApplicationContext());
        mWindowManager.addView(view, wmParams);
        Log.i(TAG, "End createFloatView--->" + mWindowManager);
        
        view.setOnTouchListener(new OnTouchListener() { 
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                Log.i(TAG, "Receive Touch Event" + event.toString());
                return false;
            }
        });

        // mFloatLayout.measure(View.MeasureSpec.makeMeasureSpec(0,
        // View.MeasureSpec.UNSPECIFIED),
        // View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

        // Log.i(TAG, "Width/2--->" + mFloatView.getMeasuredWidth() / 2);
        // Log.i(TAG, "Height/2--->" + mFloatView.getMeasuredHeight() / 2);
        // 设置监听浮动窗口的触摸移动
//         view.setOnTouchListener(new OnTouchListener() {
//        
//         @Override
//         public boolean onTouch(View v, MotionEvent event) {
//         // TODO Auto-generated method stub
//         // getRawX是触摸位置相对于屏幕的坐标，getX是相对于按钮的坐标
//         wmParams.x = (int) event.getRawX() - view.getMeasuredWidth() /
//         2;
//         Log.i(TAG, "RawX" + event.getRawX());
//         Log.i(TAG, "X" + event.getX());
//         // 减25为状态栏的高度
//         wmParams.y = (int) event.getRawY() - view.getMeasuredHeight() /
//         2 - 25;
//         Log.i(TAG, "RawY" + event.getRawY());
//         Log.i(TAG, "Y" + event.getY());
//         // 刷新
//         mWindowManager.updateViewLayout(view, wmParams);
//         return false; // 此处必须返回false，否则OnClickListener获取不到监听
//         }
//         });
        //
        // mFloatView.setOnClickListener(new OnClickListener() {
        //
        // @Override
        // public void onClick(View v) {
        // // TODO Auto-generated method stub
        // Toast.makeText(FxService.this, "onClick", Toast.LENGTH_SHORT).show();
        // }
        // });
    }

    private void drawLines(int[] intArray) {
        Bitmap newb = Bitmap.createBitmap(1080, 1920, Config.ARGB_8888);
        Canvas canvas = new Canvas(newb);
        Paint p = new Paint();
        p.setColor(Color.BLACK);
        p.setStrokeWidth(10.0f);
        for (int i = 0; i < intArray.length / 2 - 1; i++) {
            if (i < intArray.length / 2 - 2) {
                canvas.drawLine(FIRST_X + WIDTH * intArray[i * 2 + 1], FIRST_Y + HEIGHT * intArray[i * 2 + 0], FIRST_X + WIDTH * intArray[(i + 1) * 2 + 1],
                        FIRST_Y + HEIGHT * intArray[(i + 1) * 2 + 0], p);
            } else {
                drawAL(FIRST_X + WIDTH * intArray[i * 2 + 1], FIRST_Y + HEIGHT * intArray[i * 2 + 0], FIRST_X + WIDTH * intArray[(i + 1) * 2 + 1], FIRST_Y
                        + HEIGHT * intArray[(i + 1) * 2 + 0], canvas, p);
            }

        }

        view.setImageBitmap(newb);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (view != null) {
            // 移除悬浮窗口
            mWindowManager.removeView(view);
        }
    }

    private void drawAL(int sx, int sy, int ex, int ey, Canvas canvas, Paint p) {

        double H = 30; // 箭头高度
        double L = 18; // 底边的一半
        int x3 = 0;
        int y3 = 0;
        int x4 = 0;
        int y4 = 0;
        double awrad = Math.atan(L / H); // 箭头角度
        double arraow_len = Math.sqrt(L * L + H * H); // 箭头的长度
        double[] arrXY_1 = rotateVec(ex - sx, ey - sy, awrad, true, arraow_len);
        double[] arrXY_2 = rotateVec(ex - sx, ey - sy, -awrad, true, arraow_len);
        double x_3 = ex - arrXY_1[0]; // (x3,y3)是第一端点
        double y_3 = ey - arrXY_1[1];
        double x_4 = ex - arrXY_2[0]; // (x4,y4)是第二端点
        double y_4 = ey - arrXY_2[1];

        Double X3 = new Double(x_3);
        x3 = X3.intValue();
        Double Y3 = new Double(y_3);
        y3 = Y3.intValue();
        Double X4 = new Double(x_4);
        x4 = X4.intValue();
        Double Y4 = new Double(y_4);
        y4 = Y4.intValue();
        // 画线
        canvas.drawLine(sx, sy, ex, ey, p);
        //
        Path triangle = new Path();

        triangle.moveTo(ex, ey);
        triangle.lineTo(x3, y3);
        triangle.lineTo(x4, y4);
        triangle.close();
        // 实心箭头
        canvas.drawPath(triangle, p);
        // 非实心箭头
        // g2.draw(triangle);

    }

    // 计算
    private double[] rotateVec(int px, int py, double ang, boolean isChLen, double newLen) {

        double mathstr[] = new double[2];
        // 矢量旋转函数，参数含义分别是x分量、y分量、旋转角、是否改变长度、新长度
        double vx = px * Math.cos(ang) - py * Math.sin(ang);
        double vy = px * Math.sin(ang) + py * Math.cos(ang);
        if (isChLen) {
            double d = Math.sqrt(vx * vx + vy * vy);
            vx = vx / d * newLen;
            vy = vy / d * newLen;
            mathstr[0] = vx;
            mathstr[1] = vy;
        }
        return mathstr;
    }
    
    
    
    private void press(long time){
        Log.i(TAG, "press:" + time);
//        view.setVisibility(View.VISIBLE);
//        MotionEvent event = MotionEvent.obtain(downTime, eventTime, action, x, y, pressure, size, metaState, xPrecision, yPrecision, deviceId, edgeFlags);
//        MotionEvent event1 = MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, 400, 400, 0);
//        MotionEvent event2 = MotionEvent.obtain(0, 0, MotionEvent.ACTION_UP, 0, 0, 0);
//        view.onTouchEvent(event1);
        try {
            Process process;
            
            process = Runtime.getRuntime().exec("adb shell sendevent /dev/input/event10 3 58 122");
            process.waitFor();
            process = Runtime.getRuntime().exec("adb shell sendevent /dev/input/event10 3 53 400");
            process.waitFor();
            process = Runtime.getRuntime().exec("adb shell sendevent /dev/input/event10 3 54 400");
            process.waitFor();
            process = Runtime.getRuntime().exec("adb shell sendevent /dev/input/event10 3 57 0");
            process.waitFor();
            process = Runtime.getRuntime().exec("adb shell sendevent /dev/input/event10 0 2 0");
            process.waitFor();
            process = Runtime.getRuntime().exec("adb shell sendevent /dev/input/event10 0 0 0");
            process.waitFor();
            Thread.sleep(time);

            for (int i = 0; i < 1; i++) {

//                process = Runtime.getRuntime().exec("adb shell sendevent /dev/input/event10 0 2 0");
//                process.waitFor();
//                process = Runtime.getRuntime().exec("adb shell sendevent /dev/input/event10 0 0 0");
//                process.waitFor();
            }

        } catch (IOException e) {
            Log.e(TAG, "error:" + e.getMessage());
            e.printStackTrace();
        } catch (InterruptedException e) {
            Log.e(TAG, "error:" + e.getMessage());
            e.printStackTrace();
        }
    }
    
    private void srceenCap(){
//        File file = new File("/storage/sdcard1/ss.png");
//        if(file.exists()){
//            file.delete();
//        }
        try {
            Runtime.getRuntime().exec("screencap -p /storage/sdcard0/ss.png");
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }

}
